class WebAdminController < ApplicationController
  def getWebUsers
    begin
      
      pageBegin =  params[:start]
      pageEnd =  params[:limit]
      strdelData = params[:delData]
      if strdelData!=nil
        delWebUser(strdelData)
        logger.error "------------getWebUsers End Delete-----------------"
      end
      #for search
      searchType=params[:search_type]
      searchKey =params[:search_key]
      if searchType == nil
        pageWebUsers = WebUser.find(:all,:conditions=>["is_locked <> 1"])
        webUsers = WebUser.find(:all,:conditions=>["is_locked <> 1"],:limit =>pageBegin+","+pageEnd)
      else
        searchKey = "%"+searchKey+"%"
        if searchType=="user_name"
          pageWebUsers = WebUser.find(:all,:conditions => ["is_locked <> 1 AND user_name like ?","%"+searchKey+"%"])
          webUsers = WebUser.find(:all,:conditions => ["is_locked <> 1 AND user_name like ?","%"+searchKey+"%"],:limit =>pageBegin+","+pageEnd)
        elsif searchType=="user_type"
          pageWebUsers = WebUser.find(:all,:conditions => ["is_locked <> 1 AND user_type like ?","%"+searchKey+"%"])
          webUsers = WebUser.find(:all,:conditions => ["is_locked <> 1 AND user_type like ?","%"+searchKey+"%"],:limit =>pageBegin+","+pageEnd)
        end
      end
      logger.error searchType
      logger.error searchKey
      jsonstr="{totalProperty:"+pageWebUsers.length.to_s+",root:"+webUsers.to_json()+"}"
      
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  #Delete WebUser
  def delWebUser(strdelData)
    ids=""
    begin
      
      results = ActiveSupport::JSON.decode(strdelData)
      results.each do |result|
        ids << result["id"]+","
      end
      ids = ids[0,ids.length-1]
      WebUser.update_all("is_locked = 1","id in ("+ids+")")
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  # Get WebUser By ID
  def getWebUserByID
    begin
      
      webUser = WebUser.find(params[:id])
      jsonstr="{root:["+webUser.to_json(:include=>[:webUser_type,:card_type])+"]}"
      
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  def editWebUser
    begin
      webUser = WebUser.find(params[:id])
      #Clone for WebUserBackup
      webUserBK = WebUserBackup.new
      webUser.attributes.each do |attr, value|
        eval("webUserBK.#{attr}= webUser.#{attr}")
      end
      webUserBK.id =nil
      webUserBK.webUser_id=webUser.id
      webUserBK.save
      
      webUser.name=params[:name]
      webUser.sex=params[:sex]
      webUser.phone=params[:phone]
      if params[:webUser_type_id]!=""
        webUser.webUser_type_id=params[:webUser_type_id]
      end
      if params[:card_type_id]!=""
        webUser.card_type_id=params[:card_type_id]
      end
      
      webUser.card=params[:card]
      webUser.address=params[:address]
      webUser.linkman=params[:linkman]
      webUser.linkman_phone=params[:linkman_phone]
      webUser.webUser_level=params[:webUser_level]
      webUser.birthday=params[:birthday]
      webUser.user_id=session[:user_id]
      webUser.save
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  def getWebUserBaseInfoByID
    begin
      #require "json"
      logger.error "--------------------getUsers---------------------"
      webUser = WebUser.find(params[:id])
      jsonstr="{root:["+webUser.to_json()+"]}"
      
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  def setWebUserBaseInfo
    begin
      webUser = WebUser.find(params[:id])
      webUser.user_name = params[:user_name]
      webUser.sex = params[:sex]
      webUser.phone = params[:phone]
      webUser.email = params[:email]
      webUser.card = params[:card]
      webUser.address = params[:address]
      webUser.company_name = params[:company_name]
      webUser.company_phone = params[:company_phone]
      webUser.company_fax = params[:company_fax]
      webUser.post_code = params[:post_code]
      webUser.save
      render :text=>nil, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  def addWebUserBaseInfo
    begin
      webUser = WebUser.new
      webUser.user_name = params[:user_name]
      webUser.sex = params[:sex]
      webUser.phone = params[:phone]
      webUser.email = params[:email]
      webUser.card = params[:card]
      webUser.address = params[:address]
      webUser.company_name = params[:company_name]
      webUser.company_phone = params[:company_phone]
      webUser.company_fax = params[:company_fax]
      webUser.post_code = params[:post_code]
      webUser.save
      render :text=>nil, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  def getWebReturnedOrders
    begin
      
      pageBegin = params[:start]
      pageEnd = params[:limit]
      rootStr = ""
      pageWebOrders = WebOrder.find(:all,:conditions=>["is_locked <> 1 AND status = ?",Constants::WEB_ORDER_STATUS_SQTP])
      webOrders = WebOrder.find(:all,:conditions=>["is_locked <> 1 AND status = ?",Constants::WEB_ORDER_STATUS_SQTP],:limit =>pageBegin+","+pageEnd,:order=>"created_at desc")
      logger.error webOrders.size
      jsonstr="{totalProperty:"+pageWebOrders.length.to_s+",root:"+webOrders.to_json(:include=>[:web_user,:from_airport,:to_airport])+"}"
      
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      
    end
  end
  
  #得到所有已经发布的运价信息
  def getPriceReleased
    begin
      pageBegin = params[:start]
      pageEnd = params[:limit]
      strdelData = params[:delData]
      loginID =  params[:login_id]
      
      logger.error strdelData
      if strdelData!=nil
        delCommonPriceReleased(strdelData)
      end
      webUserID="%%"
      if loginID!=nil && loginID != ""
        webUserID = WebUser.find(:first,:conditions=>["login_id = ?",loginID]).id
        pageCustomers = WebPriceRelease.find(:all,:conditions=>["is_locked <> 1 AND price_type = '#{Constants::COMMON_PRICE}' AND web_user_id=?",webUserID ])
        commonPriceReleaseds = WebPriceRelease.find(:all,:conditions=>["is_locked <> 1 AND price_type = '#{Constants::COMMON_PRICE}' AND web_user_id=?",webUserID],:limit =>pageBegin+","+pageEnd)
      else
        pageCustomers = WebPriceRelease.find(:all,:conditions=>["is_locked <> 1 AND price_type = '#{Constants::COMMON_PRICE}'"])
        commonPriceReleaseds = WebPriceRelease.find(:all,:conditions=>["is_locked <> 1 AND price_type = '#{Constants::COMMON_PRICE}'"],:limit =>pageBegin+","+pageEnd)
      end
      
      jsonstr="{totalProperty:"+pageCustomers.length.to_s+",root:"+commonPriceReleaseds.to_json(:include=>[:airways,:airport_from,:web_user])+"}"
      
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  def getAllWebOrdersBySearch
    begin
      rootStr = ""
      web_user_id = session[:web_user_id]
      web_user_id = 1 if web_user_id==nil
      sql = ""
      sql << " status in('"+Constants::WEB_ORDER_STATUS_DDZF+"','"+Constants::WEB_ORDER_STATUS_ZFCG+"','"+Constants::WEB_ORDER_STATUS_CLWC+"')"
      if web_user_id
        if params[:order_no]
          order_no = params[:order_no]
          sql << " and order_no='"+order_no+"'"
        elsif params[:pnr]
          pnr = params[:pnr]
          sql << " and pnr='"+pnr+"'"
        elsif params[:passenger_name]
          pass_name = params[:passenger_name]
          pass_card = params[:passenger_card]
          sql << " and id in(select web_order_id from web_tickets where web_order_id is not null"
          sql << " and pass_name like '%"+pass_name+"%'" if pass_name && pass_name!=""
          sql << " and pass_card_id='"+pass_card+"'" if pass_card && pass_card!=""
          sql << ")"
        else
          fromdate = params[:date_begin]
          todate = params[:date_end]
          sql << " and created_at>='"+fromdate+"'" if fromdate && fromdate!=""
          sql << " and created_at<='"+todate+"'" if todate && todate!=""
        end
      end
      logger.error "sql="+sql
      weborders = WebOrder.find(:all,:conditions=>sql,:order=>"created_at desc")
      logger.error weborders.length
      for weborder in weborders
        from_airport = Airport.find_by_code(weborder.fromto[0,3])
        to_airport = Airport.find_by_code(weborder.fromto[3,3])
        fromAirport = from_airport.airport_name
        toAirport = to_airport.airport_name
        pass = ""
        for t in weborder.tickets
          pass << "/" if pass!=""
          pass << t.pass_name
        end
        rootStr << "," if rootStr!=""
        rootStr << "{"
        rootStr << "'id':'"+weborder.id.to_s+"'"
        rootStr << ",'pass':'"+pass+"'"
        rootStr << ",'order_no':'"+weborder.order_no.to_s+"'"
        rootStr << ",'pnr':'"+weborder.pnr+"'"
        rootStr << ",'trx_status':'"+weborder.trx_status.to_s+"'"
        rootStr << ",'status':'"+weborder.status.to_s+"'"
        rootStr << ",'air_no':'"+weborder.air_no+"'"
        rootStr << ",'from':'"+fromAirport[fromAirport.index(" ")+1..-1]+"'"
        rootStr << ",'to':'"+toAirport[toAirport.index(" ")+1..-1]+"'"
        rootStr << ",'position':'"+weborder.position+"'"
        rootStr << ",'fly_date':'"+weborder.fly_date.to_s+"'"
        rootStr << ",'fly_time':'"+weborder.fly_time+"'"
        rootStr << ",'fromto':'"+weborder.fromto+"'"
        rootStr << ",'platform_amount':'"+weborder.platform_amount.to_s+"'"
        rootStr << ",'created_at':'"+weborder.created_at.strftime("%Y-%m-%d %H:%M:%S")+"'"
        rootStr << ",'is_locked':'"+weborder.is_locked.to_s+"'"
        rootStr << "}"
      end
      
      #rootStr = weborders.to_json()
      jsonstr="{root:["+rootStr+"]}"
      logger.error jsonstr
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #根据订单得到票
  def getTicketsByOrderID
    begin
      id = params[:id]
      logger.error ">>>>>>>>>>>>>>>>>>>>>>"+id
      rootStr = "[]"
      if id && id.to_i>0
        tickets = WebTicket.find(:all)
        if tickets && tickets.length>0
          rootStr = tickets.to_json()
        end
      end
      jsonstr="{root:"+rootStr+"}"
      logger.error jsonstr
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end

  def setWebOrderLock
    begin
      webOrderNo = params[:order_no]
      islocked = params[:islocked]
      webOrder = WebOrder.find(:first,:conditions=>["order_no = ?",webOrderNo])
      if islocked == "true"
        webOrder.is_locked = 1
      else
        webOrder.is_locked = 0
      end
      webOrder.save
      jsonstr="SUCCESS"
      puts jsonstr
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
end
